using System;
using Ninject;
using RentalOfCars.Domain.Entities;
using RentalOfCars.Server.Domain.ClientServerInterface;

namespace RentalOfCars.Client.Presentation
{
    public class LoginWindowPresenter
    {
        private readonly IDbAccessSession _session;
        private readonly IKernel _kernel;
        private readonly ILoginWindowView _view;

        public LoginWindowPresenter(ILoginWindowView view, IDbAccessSession session, IKernel kernel)
        {
            _view = view;
            _session = session;
            _kernel = kernel;
            _view.OnLogin = OnLogin;
            _view.IsLoginButtonPressed = false;
        }

        private void OnLogin()
        {
            string login = _view.Login;
            string password = _view.Password;
            IEmployee employee;

            try
            {
                employee = _session.Login(login, password);
            }
            catch (Exception)
            {
                throw new Exception("The remote server is not available.");
            }

            if (employee == null)
            {
                var messenger = _kernel.Get<IMessenger>();
                messenger.ShowError("The user name or password is wrong.");
                return;
            }

            _view.Employee = employee;
            _view.CloseWindow();
        }
    }
}